<template>
	<el-dialog :title="title" :visible.sync="isVisible" :close-on-press-escape="false" :close-on-click-modal="false" :width="width" top="4vh">
		<el-form :model="article" ref="form" :rules="rules" v-loading="uploading">
			<el-form-item label="标题" prop="title" label-width="50px"><el-input v-model="article.title"></el-input></el-form-item>
			<el-form-item label="缩略图" style="margin-bottom: 0;">
				<div class="image-box" v-if="article.image">
					<img :src="article.image" class="image" />
					<i class="el-icon-delete-solid" @click="deleteImage"></i>
				</div>
				<i v-else class="el-icon-plus image-uploader-icon" @click="uploadImage('article')"></i>
			</el-form-item>
			<el-form-item>
				<view class="editor">
					<view class="toolbar" @click="format">
						<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
						<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
						<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian" data-name="underline"></view>
						<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike"></view>
						<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi" data-name="align" data-value="left"></view>
						<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
						<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align" data-value="right"></view>
						<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify"></view>
						<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height" data-name="lineHeight" data-value="2"></view>
						<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing" data-name="letterSpacing" data-value="2em"></view>
						<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju" data-name="marginTop" data-value="20px"></view>
						<view :class="formats.previewarginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju" data-name="marginBottom" data-value="20px"></view>
						<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
						<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font" data-name="fontFamily" data-value="Pacifico"></view>
						<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize" data-name="fontSize" data-value="24px"></view>
						<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color" data-name="color" data-value="#0000ff"></view>
						<view
							:class="formats.backgroundColor === '#00ffff' ? 'ql-active' : ''"
							class="iconfont icon-fontbgcolor"
							data-name="backgroundColor"
							data-value="#00ffff"
						></view>
						<view class="iconfont icon-date" @tap="insertDate"></view>
						<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
						<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list" data-value="ordered"></view>
						<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list" data-value="bullet"></view>
						<view class="iconfont icon-undo" @tap="undo"></view>
						<view class="iconfont icon-redo" @tap="redo"></view>
						<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
						<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
						<view class="iconfont icon-charutupian" @tap="uploadImage('editor')"></view>
						<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header" :data-value="1"></view>
						<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao" data-name="script" data-value="sub"></view>
						<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao" data-name="script" data-value="super"></view>
						<view class="iconfont icon-shanchu" @tap="clearEditor"></view>
						<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl" data-name="direction" data-value="rtl"></view>
					</view>
					<editor
						id="editor"
						class="ql-container"
						placeholder="在这里输入文章内容..."
						showImgSize
						showImgToolbar
						showImgResize
						@statuschange="onStatusChange"
						:read-only="readOnly"
						@ready="onEditorReady"
					></editor>
				</view>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="isVisible = false">取 消</el-button>
			<el-button type="primary" @click="submitForm()">确 定</el-button>
		</div>
	</el-dialog>
</template>

<script>
export default {
	name: 'articleEdit',
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		loading: {
			type: Boolean,
			default: false
		},
		type: {
			type: String,
			default: 'add'
		},
		title: {
			type: String,
			default: '添加'
		},
		article: {
			type: Object,
			default: {}
		}
	},
	data() {
		return {
			width: this.initWidth(),
			rules: {
				title: [
					{
						required: true,
						message: '请输入标题',
						trigger: 'blur'
					}
				]
			},
			readOnly: false,
			formats: {}
		};
	},
	computed: {
		isVisible: {
			get() {
				return this.visible;
			},
			set() {
				this.$emit('close');
				this.clearEditor();
			}
		},
		uploading() {
			return this.loading;
		}
	},
	watch: {
		article(e) {
			this.editorCtx.setContents({
				html: e.content
			});
		}
	},
	mounted() {
		window.onresize = () => {
			return (() => {
				this.width = this.initWidth();
			})();
		};
	},
	methods: {
		initWidth() {
			this.screenWidth = document.body.clientWidth;
			if (this.screenWidth < 991) {
				return '90%';
			} else if (this.screenWidth < 1400) {
				return '45%';
			} else {
				return '800px';
			}
		},
		onEditorReady() {
			uni.createSelectorQuery()
				.select('#editor')
				.context(res => {
					this.editorCtx = res.context;
				})
				.exec();
		},
		undo() {
			this.editorCtx.undo();
		},
		redo() {
			this.editorCtx.redo();
		},
		format(e) {
			let { name, value } = e.target.dataset;
			if (!name) return;
			this.editorCtx.format(name, value);
		},
		onStatusChange(e) {
			const formats = e.detail;
			this.formats = formats;
		},
		clearEditor() {
			this.editorCtx.clear();
		},
		removeFormat() {
			this.editorCtx.removeFormat();
		},
		insertDate() {
			const date = new Date();
			const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
			this.editorCtx.insertText({
				text: formatDate
			});
		},
		uploadImage(type) {
			uni.chooseImage({
				count: 1,
				success: images => {
					this.uploading = true;
					uniCloud.uploadFile({
						filePath: images.tempFilePaths[0],
						success: res => {
							this.uploading = false;
							if (type === 'editor') {
								this.editorCtx.insertImage({
									src: res.fileID
								});
							} else {
								this.article.image = res.fileID;
							}
						}
					});
				}
			});
		},
		deleteImage() {
			this.uploading = true;
			uniCloud.deleteFile({
				fileList: [this.article.image],
				complete: () => {
					this.uploading = false;
					this.article.image = '';
				}
			});
		},
		submitForm() {
			let article = this.article;
			if (!article.title) {
				this.$message({
					showClose: true,
					message: '文章标题不能为空',
					type: 'warning'
				});
				return;
			}
			this.editorCtx.getContents({
				success: res => {
					if (res.html === '<p><br></p>') {
						this.$message({
							showClose: true,
							message: '文章内容不能为空',
							type: 'warning'
						});
					} else {
						this.uploading = true;
						let url = 'addArticle';
						if (article._id) {
							url = 'updateArticle';
							article.id = article._id;
							delete article['_id'];
							article.update_date = new Date().toLocaleString();
						} else {
							article.create_date = new Date().toLocaleString();
						}
						uniCloud
							.callFunction({
								name: url,
								data: {
									...article,
									delete_date: '0',
									content: res.html
								}
							})
							.then(res => {
								this.uploading = false;
								this.isVisible = false;
								this.$message({
									showClose: true,
									message: '操作成功',
									type: 'success'
								});
								this.$emit('success');
							});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
@import '@/static/css/editor-icon.css';
.iconfont {
	display: inline-block;
	padding: 8px 8px;
	width: 24px;
	height: 24px;
	cursor: pointer;
	font-size: 20px;
}

.toolbar {
	box-sizing: border-box;
	border-bottom: 0;
	font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	margin-top: 5px;
}

.ql-container {
	box-sizing: border-box;
	padding: 10px 10px;
	width: 100%;
	min-height: 20vh;
	height: auto;
	background: #fff;
	font-size: 16px;
	line-height: 1.5;
}

.ql-active {
	color: #06c;
}

.article-box {
	height: 100%;
	padding: 10px;
	box-sizing: border-box;

	.btn-box {
		margin-bottom: 10px;

		.btn {
			margin-right: 10px;
		}
	}

	.el-pagination {
		margin-top: 20px;
	}
}

.image-box {
	position: relative;
	width: 120px;
	height: 120px;
	margin-left: 50px;

	.image {
		width: 120px;
		height: 120px;
		position: absolute;
		left: 0;
		top: 0;
	}

	.el-icon-delete-solid {
		color: red;
		position: absolute;
		bottom: 0;
		right: 0;
		font-size: 20px;
	}
}

.ql-editor {
	padding: 0;
}

.image-uploader-icon {
	border: 1px dashed #55aaff;
	font-size: 28px;
	color: #8c939d;
	width: 120px;
	height: 120px;
	line-height: 120px;
	text-align: center;
}
</style>
